<?php

class DichvuController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column1';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
			//'postOnly + delete', // we only allow deletion via POST request
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('view'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update', 'muadichvu','muadichvu2', 'history','suggestDichvu','getJson'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('index','admin','delete','orderadmin','exportorder', 'gia','listgiauser', 'tracode', 'xoa', 'quickaccess'),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new Dichvu;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Dichvu']))
		{
			$model->attributes=$_POST['Dichvu'];
			$model->trangthai = 1;
			if($model->save())
				$this->redirect(array('view','id'=>$model->id));
		}

		$criteria = new CDbCriteria();
		$criteria->compare('trangthai', 1);
		$var =Nhomdichvu::model()->findAll($criteria);
		$data['nhomdichvu'] = CHtml::listData($var, "id", "tennhom");
		$data['model'] = $model;
		$this->render('create',$data);
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Dichvu']))
		{
			$model->attributes=$_POST['Dichvu'];
			//if($model->save())
			 Dichvudao::update($model);
				$this->redirect(array('view','id'=>$model->id));
		}

		$var =Nhomdichvu::model()->findAll();
		$data['nhomdichvu'] = CHtml::listData($var, "id", "tennhom");
		$data['model'] = $model;
		$this->render('update',$data);
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	
	public function actionDelete($id)
	{
		Dichvudao::delete($id);
		$this->redirect(array('index'));
	}
	
	public function actionXoa($id)
	{
		Dichvudao::delete($id);
		$this->redirect(array('index'));
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		/*
		$criteria = new CDbCriteria();
		$criteria->compare('trangthai',1);
		$Page = new CPagination(Dichvu::model()->count($criteria));
		//$Page->pageSize = Yii::app()->params['listPerPage'];
		$Page->pageSize = 25;
		$Page->applyLimit($criteria);		            
		$this->render('index', array(
		    'model' => Dichvu::model()->findAll($criteria),
		    'pages' => $Page
		));
	*/
		$criteria=new CDbCriteria;
		$criteria->compare('trangthai',1);
		$model = Dichvu::model()->findAll($criteria);
		$this->render('index', array('model'=>$model));
		
		
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new Dichvu('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Dichvu']))
			$model->attributes=$_GET['Dichvu'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=Dichvu::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='dichvu-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
	
	public function actionMuaDichVu($id){
		if(!isset($id)){
			$this->redirect('muadichvu2');
		}
		
		
		$imei ='';
		$dichvu = Dichvu::model()->findByPK($id);
		$iduser = UserUtils::getUserId();
		$cre = Credit::model()->findByAttributes(array('iduser'=>$iduser));
		$gia =$dichvu->gia;
		$giauser = GiadichvuUser::model()->findByAttributes(array('iduser'=>$iduser, 'iddichvu'=>$id));
		if($giauser != null ){
			$gia =$giauser->gia;
		}
			
		if(isset($_REQUEST['imei'])){
			$imei = $_REQUEST['imei'];
			$list = explode("\n", $imei);
			$listImei=Array();
			$count = count($list);

	/*		for($i=0;$i<$count;$i++)
			{				
				if(strlen($list[$i])!=15)
				{
					unset($list[$i]);		
				}							
			}
			
			*/
			$cre = Credit::model()->findByAttributes(array('iduser'=>$iduser));
			if(count($list) * $gia > $cre->sodu){
				echo "Bạn không đủ credit order, vui lòng nạp thêm tài khoản";
				print_r($list);
				die();
			}
			
			// trừ credit
			
			//$cre->sodu = $cre->sodu - (count($listImei) * $gia);
			//$cre->update();
			
			$currentdate =  DateUtils::getNow();
			foreach ($list as $item){
				$model = new Muadichvu;
				$model->iduser = $iduser;
				$model->noidung = $item;
				$model->iddichvu = $id;
				$model->gia = $gia;
				$model->ngaymua = $currentdate;
				$model->trangthai = 0;
				$model->save();
			}
			$user = User::model()->findByPK($iduser);
			$tongsotien = count($list) * $gia;
			// tru tien va gui mail tru tien
			Creditdao::truCredit($cre, $tongsotien, $user, $imei);
			// gui mail order
			EmailUtils::sendemailOrder($list, $gia, $user);
			Yii::app()->user->setId($user);
			$this->redirect(array('history'));
		}
		
		$this->render('muadichvu', array('imei'=>$imei, 'dichvu'=> $dichvu, 'gia'=>$gia,'cre'=>$cre));
	}
	
	public function actionMuaDichVu2(){
		$imei ='';
		$items =  Dichvu::model()->findAll();
		$dichvu = new Dichvu;
		foreach ($items as $item){
			$dichvu = $item;
			break;
		}
		$iduser = UserUtils::getUserId();
		$id = $dichvu->id;
		if(isset($_POST['id'])){
			$id =$_POST['id'];
		}
		$dichvu = Dichvu::model()->findByPK($id);
		
		$gia =$dichvu->gia;
		$giauser = GiadichvuUser::model()->findByAttributes(array('iduser'=>$iduser, 'iddichvu'=>$id));
			if($giauser != null ){
				$gia =$giauser->gia;
			}
		$cre = Credit::model()->findByAttributes(array('iduser'=>$iduser));
		if(isset($_POST['imei']) && isset($_POST['id'])){
			$imei = $_POST['imei'];
			$list = explode("\n", $imei);
			$listImei=Array();
			$j=0;
		/*	for($i=0;$i<count($list);$i++)
			{
				if(strlen($list[$i])==15)
				{
					$listImei[$j]=$list[$i];	
					$j++;			
				}				
			}*/
			// kiểm tra số dư credit
			
			
			
			$cre = Credit::model()->findByAttributes(array('iduser'=>$iduser));
			
			if(count($list) * $gia > $cre->sodu){
				echo "Bạn không đủ credit order, vui lòng nạp thêm tài khoản";
				die();
			}
			
			// trừ credit
			
			//$cre->sodu = $cre->sodu - (count($listImei) * $gia);
			//$cre->update();
			
			$currentdate =  DateUtils::getNow();
			foreach ($list as $item){
				$model = new Muadichvu;
				$model->iduser = $iduser;
				$model->noidung = $item;
				$model->iddichvu = $dichvu->id;
				$model->gia = $gia;
				$model->ngaymua = $currentdate;
				$model->trangthai = 0;
				$model->save();
				//print_r( $model->attributes);
			}
			//die();
			
			$user = User::model()->findByPK($iduser);
			$tongsotien = count($list) * $gia;
			// tru tien va gui mail tru tien
			Creditdao::truCredit($cre, $tongsotien, $user, $imei);
			// gui mail order
			EmailUtils::sendemailOrder($list, $gia, $user);
			
			Yii::app()->user->setId($user);
			$this->redirect(array('history'));
		}
		
		$nhomdichvu = Dichvudao::getlist(true);
		$data['nhomdichvu'] = CHtml::listData( $nhomdichvu,'id','tendichvu');
		$data['dichvu'] = $dichvu;
		$data['gia']=$gia;
		$data['cre']=$cre;
		$this->render('muadichvu2', $data);
	
	}
	
	/*Json autocomplete Create.php*/
	public function actionSuggestDichvu() {
		$criteria = new CDbCriteria;
		$criteria->select = array('id', 'tendichvu');
	
		$criteria->addSearchCondition('tendichvu',  strtoupper( $_GET['term']) ) ;
		$criteria->limit = 15;
		$data = Dichvu::model()->findAll($criteria);
	
		$arr = array();
	
		foreach ($data as $item) {
			 
			$arr[] = array(
					'id' => $item->id,
					'value' => $item->tendichvu,
					'label' => $item->tendichvu,
			);
		}
	
		echo CJSON::encode($arr);
	
	}
	
	
	public function actionHistory(){
		$listhistory = Dichvudao::listHistory();
		$this->render('history', $listhistory);
	}
	
	public function actionOrderAdmin(){
		if(isset($_REQUEST['orders']))
		{
			$arr = $_REQUEST['orders'];
			$request = explode(',', $arr);
			//print_r($request);
			//die();
			Dichvudao::changeState($_REQUEST['ordertype'],$request);
		}
		
		if(isset($_REQUEST['type'])){
			switch($_REQUEST['type']){
				case "order":
					 $listorders = Dichvudao::listOrder(0);
					$this->render('_orders' , array('listorders' => $listorders));
					break;
				case "pendding1":
					$this->render('_orderpendding', array('trangthai'=>1));
					break;
				case "pendding2":
					$this->render('_orderpendding', array('trangthai'=>12));
					break;
				case "done":
					$listunlock = Dichvudao::listOrder(2);
					$this->render('_orderunlock', array('listunlock'=>$listunlock));
					break;
				case "refund":
					$this->render('_orderrefund');
					break;
			}
		}else{
			 $listorders = Dichvudao::listOrder(0);
			$this->render('_orders' , array('listorders' => $listorders));
		}
	}
	
	public function actionExportOrder(){
		
    $data = Muadichvu::model()->findAll();
    $filename = 'orders-'. DateUtils::getNow();
    if(isset($_REQUEST['trangthai'])){
    	$criteria = new CDbCriteria();
		$criteria->order = 'iddichvu ASC, ngaycapnhat DESC, ngaymua DESC';
		$criteria->compare('trangthai',$_REQUEST['trangthai']);
    	$data = Muadichvu::model()->findAll($criteria);
    	switch($_REQUEST['trangthai']){
    		case 0:
    			 $filename = 'orders-'. DateUtils::getNow();
    			 break;
    		 case 1:
	    		 $filename = 'pendding-'. DateUtils::getNow();
	    		 break;
    		 case 2:
	    		 $filename = 'unlocked-'. DateUtils::getNow();
	    		 break;
    		 case 3:
	    		 $filename = 'refund-'. DateUtils::getNow();
	    		 break;
    	}
    }
    
    for($i=0; $i < count($data); $i++){
    	$data[$i]->iduser = $data[$i]->tbuser->username;
    	$data[$i]->iddichvu = $data[$i]->tbdichvu->tendichvu;
    }
    
	Yii::import('application.extensions.phpexcel.JPhpExcel');
	$xls = new JPhpExcel('UTF-8', false, 'My Test Sheet');
	$xls->addArray($data);
	$xls->generateXML($filename);
	}
	
	public function actionGia(){
		$model = new GiadichvuUser;
		if(isset($_POST['GiadichvuUser'])){
			$model->attributes = $_POST['GiadichvuUser'];
			if($model->validate()){
				GiaDichvuUserdao::setGia($model);
				$this->redirect(array('listgiauser', 'iduser'=>$model->iduser));
			}
		}
		$user =User::model()->findAll();
		$data['users'] = CHtml::listData($user, "id", "username");
		$dichvu =Dichvu::model()->findAll();
		$data['dichvu'] = CHtml::listData($dichvu, "id", "tendichvu");
		$data['model'] = $model;
		$this->render('gia', $data);
	}
	
	public function actionListGiaUser(){
		$iduser = $_REQUEST['iduser'];
		$model = GiaDichvuUserdao::getlistByidUser($iduser);
		$user = User::model()->findByPK($iduser);
		$data['user'] = $user;
		$data['model'] = $model;
		$this->render('listgiauser', $data);
	}
	
	public function actionTraCode($id){
		$model = Muadichvu::model()->findByPK($id);
		if(isset($_REQUEST['Muadichvu'])){
			$dichvu = new Muadichvu;
			$dichvu->attributes = $_REQUEST['Muadichvu'];
			Dichvudao::traCode($model, $dichvu->ketqua);
			$this->redirect(array('orderadmin'));
		}
		
		$this->render('tracode', array("model"=>$model));
	}
	
	//autocomplete action
	
	
	//json click chon combobox	
	public function actiongetJson() /* ajax function */
	{		
		$event = Dichvu::model()->findByPk($_POST['id']);		
		$gia = $event->gia;
		$giauser = GiadichvuUser::model()->findByAttributes(array('iddichvu'=>$_POST['id'], 'iduser'=>$_POST['iduser']));
		if($giauser != null){
			$gia = $giauser->gia;
		}
		$return_array = array(
				'data'=>array(
						'gia'=>$gia,
							
						'id'=>$event->id,
				),
		);
		echo json_encode($return_array);
	}
	
	public function actionQuickAccess(){
		$this->render('quickaccess');
	}
}
